package com.geoai.uimap.core.mapbox

import com.mapbox.mapboxsdk.geometry.LatLng
import com.mapbox.mapboxsdk.plugins.annotation.Line
import com.mapbox.mapboxsdk.plugins.annotation.LineManager
import com.mapbox.mapboxsdk.plugins.annotation.LineOptions
import com.mapbox.mapboxsdk.utils.ColorUtils
import com.geoai.uimap.api.IGEOMap
import com.geoai.uimap.api.GEOMapPolyline
import com.geoai.uimap.geo.ILatLng
import com.geoai.uimap.utils.getMapBoxGeometry

class MapboxPolyline(private val map: IGEOMap) : GEOMapPolyline() {


    private var mLine: Line? = null
    override fun show(): GEOMapPolyline {
        if (mPoints.isNullOrEmpty()) return this
        val mapBoxGeometry = map.getMapBoxGeometry() ?: return this
        getLineManager(mapBoxGeometry)?.let {
            val lineLatLngs: MutableList<LatLng> = ArrayList()
            mPoints?.forEach { p ->
                lineLatLngs.add(LatLng(p.latitude, p.longitude))
            }
            val lineOptions = LineOptions()
                    .withLatLngs(lineLatLngs)
                    .withLineColor(ColorUtils.colorToRgbaString(mLineColor))
                    .withLineWidth(mWidth)
            mLine = it.create(lineOptions)
        }

        return this
    }

    override fun setPositions(positions: List<ILatLng>): GEOMapPolyline {
        mLine?.let { line ->
            val lineLatLngs: MutableList<LatLng> = ArrayList()
            positions.forEach { p ->
                lineLatLngs.add(LatLng(p.latitude, p.longitude))
            }
            line.latLngs = lineLatLngs
            map.getMapBoxGeometry()?.let {
                getLineManager(it)?.update(line)
            }
        }
        this.mPoints = positions
        return this
    }

    private fun getLineManager(mapBoxGeometry: MapboxGeometryManager): LineManager? {
        return if (mDotted) mapBoxGeometry.getDottedLineManager() else mapBoxGeometry.getLineManager()
    }

    override fun destroy() {
        mLine?.let { line ->
            map.getMapBoxGeometry()?.let {
                getLineManager(it)?.delete(line)
            }
        }
    }


}